
class HttpUtil {
  async get(url) {
    const response = await fetch(url)
    const result = this.parseResponse(response)
    return result
  }

  async post(url, params) {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(params)
    })
    return response.json()
  }

  checkStatus(response) {
    const { status } = response
    console.log('checkStatus status', status)
    if (status !== 200) {
      return false
    }
    return true
  }

  parseResponse(response) {
    const contentType = response.headers.get('Content-Type')
    console.log('parseResponse contentType', contentType.indexOf('json'))
    if (contentType != null) {
      if (contentType.indexOf('text') > -1) {
        return response.text()
      }
      if (contentType.indexOf('form') > -1) {
        return response.formData()
      }
      if (contentType.indexOf('video') > -1) {
        return response.blob()
      }
      if (contentType.indexOf('json') > -1) {
        return response.json()
      }
    }
    return response.text()
  }
}

const httpUtil = new HttpUtil()
export default httpUtil
